﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class FormClientForModbusRTU : Form
    {
        private List<TcpClient> clients = new List<TcpClient>();
        private List<TextBox> inputBoxes = new List<TextBox>();
        private List<TextBox> logBoxes = new List<TextBox>();

        public FormClientForModbusRTU()
        {
            InitializeComponent();
            InitializeCustomComponents();
        }

        private void InitializeCustomComponents()
        {
            // IP Address Label
            Label lblIpAddress = new Label
            {
                Text = "IP Address:",
                Location = new Point(10, 10),
                AutoSize = true
            };
            Controls.Add(lblIpAddress);

            // IP Address TextBox
            TextBox txtIpAddress = new TextBox
            {
                Location = new Point(100, 10),
                Width = 150,
                Text="127.0.0.1"
            };
            Controls.Add(txtIpAddress);

            // Port Label
            Label lblPort = new Label
            {
                Text = "Port:",
                Location = new Point(10, 40),
                AutoSize = true,
                
            };
            Controls.Add(lblPort);

            // Port TextBox
            TextBox txtPort = new TextBox
            {
                Location = new Point(100, 40),
                Width = 150,
                Text = "502"
            };
            Controls.Add(txtPort);

            // Client Count Label
            Label lblClientCount = new Label
            {
                Text = "Client Count:",
                Location = new Point(10, 70),
                AutoSize = true
            };
            Controls.Add(lblClientCount);

            // Client Count TextBox
            TextBox txtClientCount = new TextBox
            {
                Location = new Point(100, 70),
                Width = 150,
                Text="3"
            };
            Controls.Add(txtClientCount);

            // Connect Button
            Button btnConnect = new Button
            {
                Text = "Connect",
                Location = new Point(10, 100),
                Width = 240
            };
            btnConnect.Click += async (sender, e) => await ConnectClients(txtIpAddress.Text, int.Parse(txtPort.Text), int.Parse(txtClientCount.Text));
            Controls.Add(btnConnect);
        }

        private async Task ConnectClients(string ipAddress, int port, int clientCount)
        {
            for (int i = 0; i < clientCount; i++)
            {
                TcpClient client = new TcpClient();
                await client.ConnectAsync(ipAddress, port);
                clients.Add(client);

                // Create input box for each client
                TextBox txtInput = new TextBox
                {
                    Location = new Point(10, 130 + i * 60),
                    Width = 200
                };
                Controls.Add(txtInput);
                inputBoxes.Add(txtInput);

                // Create send button for each client
                Button btnSend = new Button
                {
                    Text = "Send",
                    Location = new Point(220, 130 + i * 60),
                    Tag = i
                };
                btnSend.Click += (sender, e) => SendData((int)((Button)sender).Tag);
                Controls.Add(btnSend);

                // Create log box for each client
                TextBox txtLog = new TextBox
                {
                    Location = new Point(10, 160 + i * 60),
                    Width = 300,
                    Height = 50,
                    Multiline = true,
                    ReadOnly = true
                };
                Controls.Add(txtLog);
                logBoxes.Add(txtLog);
            }
        }

        private void SendData(int clientIndex)
        {
            if (clientIndex < clients.Count && clientIndex < inputBoxes.Count)
            {
                TcpClient client = clients[clientIndex];
                TextBox txtInput = inputBoxes[clientIndex];
                TextBox txtLog = logBoxes[clientIndex];
                string message = txtInput.Text;
                byte[] data = Encoding.UTF8.GetBytes(message);
                NetworkStream stream = client.GetStream();
                stream.Write(data, 0, data.Length);

                // Log the sent message
                txtLog.AppendText($"Sent: {message}\r\n");

                // Read the response
                Task.Run(async () =>
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);

                    // Log the received message
                    txtLog.Invoke((Action)(() => txtLog.AppendText($"Received: {response}\r\n")));
                });
            }
        }
    }
}